package me.zxk.qwert_poetry.config;


import me.zxk.qwert_poetry.util.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer  {

    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 鉴权拦截器
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/api/**");
    }

    // 解决使用 GlobalControllerHandler 后若 endpoint 返回 String 类型会报 CastException 的问题
    // https://stackoverflow.com/questions/44121648/controlleradvice-responsebodyadvice-failed-to-enclose-a-string-response

    // 补充：增加后会 MappingJackson2HttpMessageConverter 导致 Swagger 无法正常使用
    // 解决：应当再加一个 ByteArrayHttpMessageConverter
    // https://stackoverflow.com/questions/72485521/the-provided-definition-does-not-specify-a-valid-version-field-when-render-opena
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        WebMvcConfigurer.super.configureMessageConverters(converters);
        converters.add(0, new MappingJackson2HttpMessageConverter());
        converters.add(0, new ByteArrayHttpMessageConverter());
    }
}
